package ru.minidoc.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.minidoc.model.User;

public class LoginFilter implements Filter {

    private FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    public void destroy() {
        filterConfig.getServletContext().log(":: PostLoginFilter - destroy");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        User user = (User) httpRequest.getSession().getAttribute("user");

        if (user == null) {

            httpRequest.setAttribute("errors",
                    "You must log in to access the page you requested.");

            // don't overwrite the original request path if already present
            String requestedUrl = (String) httpRequest.getSession()
                    .getAttribute("requestedUrl");
            if (requestedUrl != null) {

                httpRequest.getSession().setAttribute("requestedUrl",
                        requestedUrl);

            } else {
                requestedUrl = httpRequest.getRequestURL().toString();
                if (httpRequest.getQueryString() != null) {
                    requestedUrl = requestedUrl + "?"
                            + httpRequest.getQueryString();
                }
                httpRequest.getSession().setAttribute("requestedUrl",
                        requestedUrl);
            }

            request.getRequestDispatcher("/login.page").forward(httpRequest,
                    httpResponse);
        } else {
            request.setAttribute("adminMode", "admin".equalsIgnoreCase(user.getLogin()));
            request.setAttribute("managerMode", user.isManager());
            // user is logged in; move on down the chain
            chain.doFilter(request, response);
        }
    }
}
